﻿using DimensionsHelper.LanguageService.Syntax;

namespace DimensionsHelper.LanguageService;

/// <summary>
///     保存错误信息的临时对象
/// </summary>
/// <param name="location">错误所在的语法位置</param>
/// <param name="descriptor">错误描述</param>
/// <param name="messageArgs">格式化错误信息的参数</param>
public class DiagnosticInfo(in SyntaxLocation location, DiagnosticDescriptor descriptor, object?[]? messageArgs)
{
    /// <summary>
    ///     错误所在的语法位置
    /// </summary>
    public SyntaxLocation Location { get; } = location;

    /// <summary>
    ///     错误描述信息
    /// </summary>
    public DiagnosticDescriptor Descriptor { get; } = descriptor;


    /// <summary>
    ///     格式化错误信息使用的参数列表，格式化使用string.Format方法格式化字符串，
    ///     此处保存的参数信息也应当符合该方法的要求。
    /// </summary>
    public object?[]? MessageArgs { get; } = messageArgs;


    /// <summary>
    ///     当前报错信息关联的其他错误信息。
    /// </summary>
    public List<DiagnosticInfo> Related { get; } = [];


    public override string ToString()
    {
        string res =
            $"{GetMessage()} {Location}";

        for (int i = Related.Count - 1; i >= 0; i--)
        {
            res += Environment.NewLine +
                   $"{Related[i].GetMessage()} [{Related[i].Location})";
        }

        return res;
    }


    private string GetMessage()
    {
        return MessageArgs == null
            ? Descriptor.MessageFormat
            : string.Format(Descriptor.MessageFormat, MessageArgs);
    }
}